package com.shuangseqiu.controller;

import com.shuangseqiu.service.PredictionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 预测控制器，提供HTTP API接口
 */
@RestController
@RequestMapping("/api/prediction")
public class PredictionController {

    private static final Logger logger = LoggerFactory.getLogger(PredictionController.class);
    
    @Autowired
    private PredictionService predictionService;

    /**
     * 分析单个网页的端点
     *
     * @param url 要分析的网页URL
     * @return 分析结果
     */
    @PostMapping("/analyze")
    public ResponseEntity<?> analyzeWebPage(@RequestBody Map<String, String> requestBody) {
        try {
            String url = requestBody.get("url");
            
            if (url == null || url.isEmpty()) {
                return ResponseEntity.badRequest().body("URL不能为空");
            }
            
            logger.info("接收到网页分析请求: {}", url);
            
            // 调用服务层进行分析
            Map<String, Object> result = predictionService.analyzeWebPageContent(url);
            
            // 保存结果到今天的日期文件中
            String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            predictionService.saveResultToJson(result, currentDate + "_single");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("网页分析请求处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 分析多个网页的端点
     *
     * @param requestBody 包含URL列表的请求体
     * @return 综合分析结果
     */
    @PostMapping("/analyze-multiple")
    public ResponseEntity<?> analyzeMultipleWebPages(@RequestBody Map<String, String[]> requestBody) {
        try {
            String[] urls = requestBody.get("urls");
            
            if (urls == null || urls.length == 0) {
                return ResponseEntity.badRequest().body("URL列表不能为空");
            }
            
            logger.info("接收到多网页分析请求，共 {} 个URL", urls.length);
            
            // 调用服务层进行分析
            Map<String, Object> result = predictionService.analyzeMultipleWebPages(urls);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("多网页分析请求处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 获取指定日期的分析结果
     *
     * @param date 指定的日期，格式为yyyyMMdd
     * @return 分析结果文件内容
     */
    @GetMapping("/results/{date}")
    public ResponseEntity<?> getResultsByDate(@PathVariable("date") @DateTimeFormat(pattern = "yyyyMMdd") Date date) {
        try {
            String dateStr = new SimpleDateFormat("yyyyMMdd").format(date);
            String filePath = Paths.get("./data", dateStr + ".json").toString();
            
            File resultFile = new File(filePath);
            if (!resultFile.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到指定日期的结果文件");
            }
            
            logger.info("获取日期 {} 的分析结果", dateStr);
            
            // 读取文件内容
            String content = new String(Files.readAllBytes(Paths.get(filePath)));
            
            return ResponseEntity.ok()
                    .header("Content-Type", "application/json")
                    .body(content);
            
        } catch (IOException e) {
            logger.error("读取结果文件失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", "读取结果文件失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        } catch (Exception e) {
            logger.error("获取结果请求处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 获取当前日期的分析结果
     *
     * @return 当前日期的分析结果
     */
    @GetMapping("/results/today")
    public ResponseEntity<?> getTodayResults() throws ParseException {
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        return getResultsByDate(new SimpleDateFormat("yyyyMMdd").parse(today));
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    public ResponseEntity<?> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("timestamp", new Date());
        response.put("message", "双色球预测分析服务运行正常");
        return ResponseEntity.ok(response);
    }
}